package com.jerry.usbserial.fragment.usb

import android.content.*
import android.os.*
import com.jerry.usbserial.activity.UsbService
import com.jerry.usbserial.fragment.BaseFragment
import com.jerry.usbserial.util.MsgEvent
import com.jerry.usbserial.util.MsgEventCode
import com.jerry.usbserial.util.postState
import com.jerry.usbserial.util.task.usb.UsbTask

/**
 * Created by dugang on 2020/7/5.
 */
abstract class UsbFragment : BaseFragment() {
    private var mUsbService: UsbService? = null
    private var mDeviceConnected: Boolean = false
    private var mUsbTask: UsbTask? = null


    override fun onResume() {
        super.onResume()
        registerReceiver()
        bindService()
    }

    override fun onPause() {
        super.onPause()
        mContext.unregisterReceiver(mUsbReceiver)
        mContext.unbindService(usbConnection)
    }

    private fun registerReceiver() {
        mContext.registerReceiver(mUsbReceiver, IntentFilter().apply {
            addAction(UsbService.ACTION_USB_PERMISSION_GRANTED)
            addAction(UsbService.ACTION_NO_USB)
            addAction(UsbService.ACTION_USB_DISCONNECTED)
            addAction(UsbService.ACTION_USB_NOT_SUPPORTED)
            addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED)
        })
    }

    private fun bindService() {
        if (!UsbService.SERVICE_CONNECTED) {
            if (Build.VERSION.SDK_INT >= 26) {
                mContext.startForegroundService(Intent(mContext, UsbService::class.java))
            } else {
                mContext.startService(Intent(mContext, UsbService::class.java))
            }
        }
        mContext.bindService(Intent(mContext, UsbService::class.java), usbConnection, Context.BIND_AUTO_CREATE)
    }


    private val mHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                UsbService.MESSAGE_FROM_SERIAL_PORT -> mUsbTask?.onResult(msg.obj as ByteArray)
                UsbService.CTS_CHANGE -> MsgEvent(MsgEventCode.STATE, "CTS通道")
                UsbService.DSR_CHANGE -> MsgEvent(MsgEventCode.STATE, "DSR通道")
            }
        }
    }


    private val usbConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(arg0: ComponentName, arg1: IBinder) {
            mUsbService = (arg1 as UsbService.UsbBinder).service
            mUsbService?.setHandler(mHandler)
        }

        override fun onServiceDisconnected(arg0: ComponentName) {
            mUsbService = null
        }
    }


    private val mUsbReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            mDeviceConnected = false
            when (intent.action) {
                UsbService.ACTION_USB_PERMISSION_GRANTED -> {
                    mUsbTask?.onResult(byteArrayOf())
                    mDeviceConnected = true
                    postState("设备已连接")
                }
                UsbService.ACTION_USB_PERMISSION_NOT_GRANTED -> {
                    postState("设备连接失败")
                }
                UsbService.ACTION_NO_USB -> {
                    postState("暂无设备连接")
                }
                UsbService.ACTION_USB_DISCONNECTED -> {
                    mUsbTask?.disconnect()
                    postState("设备已断开")
                }
                UsbService.ACTION_USB_NOT_SUPPORTED -> {
                    postState("不支持该设备")
                }
                else -> {
                    postState("未知状态")
                }
            }
        }
    }

    fun isDeviceConnected(): Boolean = mDeviceConnected

    fun getUsbService(): UsbService? = mUsbService

    fun startTask(task: UsbTask) {
        mUsbTask = task
        mUsbTask!!.start()
    }


    fun hasTask(): Boolean = mUsbTask != null

    protected fun closeTask() {
        mUsbTask?.close()
        mUsbTask = null
    }
}